package com.morphiastic;

import java.io.IOException;

import org.elasticsearch.common.xcontent.XContentBuilder;

/**
 * 
 * Default implementation of an IndexWorker for async indexing
 * 
 * 
 * Should it be nested inside ElasticStore ??? 
 * 
 * @author Alex
 *
 */
public class DefaultSaveToIndexWorker implements IndexWorker {

	private IndexedClass indexedClass;
	private Object entity;
	private ElasticStore elasticStore;
	 
	public DefaultSaveToIndexWorker( IndexedClass indexedClass, Object entity, ElasticStore elasticStore){
		this.indexedClass = indexedClass;
		this.entity = entity;
		this.elasticStore = elasticStore;
	}
	
	@Override
	public void run() {
		elasticStore.firePreIndexEvent(indexedClass.getClazz(), entity);
		try {
			XContentBuilder x = indexedClass.indexObject(elasticStore.getGlobalIndexName(),  entity,  elasticStore.getClient());
			elasticStore.firePostIndexEvent(  indexedClass.getClazz(),   entity, x );
		} catch (IOException e) {
			elasticStore.fireEntityIndexationError(indexedClass.getClazz(), entity, e);
		}
	}
}
